package com.szlanyou.tcp_server_demo;

import com.szlanyou.tcp_server_demo.adapter.ClientItemModel;
import com.szlanyou.tcpservermaster.TcpClientItem;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 陈章
 * create at 2021/1/20 17:19
 * desc:客户端管理池
 */
public class ClientPool {
    public Map<String, ClientItemModel> clientMap = new HashMap<>();
    private OnPoolChangedListener onPoolChangedListener;

    public void join(TcpClientItem tcpClient){
        ClientItemModel clientItemModel = new ClientItemModel();
        clientItemModel.tcpClient = tcpClient;
        clientItemModel.setActivated(true);
        clientItemModel.protocolHandlerSingleton.get().start();
        clientMap.put(tcpClient.getAddress(),clientItemModel);
        onPoolChanged();
    }

    public void leave(TcpClientItem tcpClient){
        ClientItemModel clientItemModel = new ClientItemModel();
        clientItemModel.tcpClient = tcpClient;
        clientItemModel.setActivated(false);
        clientItemModel.protocolHandlerSingleton.get().release();
        clientMap.put(tcpClient.getAddress(),clientItemModel);
        onPoolChanged();
    }

    public ClientItemModel get(String address){
        return clientMap.get(address);
    }

    public void release(){
        List<ClientItemModel> list = getList();
        for (ClientItemModel item : list){
            item.protocolHandlerSingleton.get().release();
        }
    }

    private void onPoolChanged(){
        if(onPoolChangedListener != null){
            onPoolChangedListener.onPoolChange(getList());
        }
    }
    public List<ClientItemModel> getList(){
        Collection<ClientItemModel> values = clientMap.values();
        return  new ArrayList<>(values);
    }

    public void setOnPoolChangedListener(OnPoolChangedListener onPoolChangedListener) {
        this.onPoolChangedListener = onPoolChangedListener;
    }

    public interface OnPoolChangedListener{
        /**
         * 客户端加入或者离开
         * @param list
         */
        void onPoolChange(List<ClientItemModel> list);
    }
}
